<template>
  <div class="add-box">
    <w-form-validate @on-validate="saveAddEmployee">
      <div class="e-add">
        <!-- 员工信息 -->
        <div class="e-item">
          <span class="title">用户名</span>
          <div class="o-select dis-block">
            <w-input :holder="`请输入用户名`" v-model="addParams.userName" rule="isEmpty" error="*此项必填" :disabled="isEdit" @on-blur='checkUserName' ref='nameInput'></w-input>
          </div>
        </div>
        <div class="e-item">
          <span class="title">角色</span>
          <div class="o-select dis-block">
            <w-select :options="roleList" v-model="addParams.roleId" @on-select='changeRole' v-if="!isEdit"></w-select>
            <w-input v-model="name.role" v-if="isEdit" :disabled="true"></w-input>
          </div>
        </div>
        <div class="e-item">
          <span class="title">部门</span>
          <div class="o-select dis-block">
            <w-select :options="departList" v-model="addParams.departmentId" v-if="!isEdit"></w-select>
            <w-input v-model="name.depart" v-if="isEdit" :disabled="true"></w-input>
          </div>
        </div>
        <div class="e-item">
          <span class="title">花名</span>
          <div class="o-select dis-block">
            <w-input :holder="`请填写`" v-model="addParams.alias" :disabled="isEdit"  rule="isEmpty" error="*此项必填"></w-input>
          </div>
        </div>
        <div class="e-item" v-if='!$route.query.id'>
          <span class="title">设置密码</span>
          <div class="o-select dis-block">
            <w-input type='password' holder="请填写密码" v-model="addParams.password" rule="isEmpty|isPassword" error="*此项必填"></w-input>
          </div>
        </div>
        <div class="e-item" v-if='!$route.query.id'>
          <span class="title">确认密码</span>
          <div class="o-select dis-block">
            <w-input type='password' :holder="`请确认密码`" v-model="addParams.twoPassword" rule="isEmpty" error="*此项必填" @on-blur='checkPwassword' ref='rePwdInput'></w-input>
          </div>
        </div>
        <div class="e-item">
          <span class="title">员工邮箱</span>
          <div class="o-select dis-block">
            <w-input :holder="`请填写`" v-model="addParams.mail" rule="isEmail" error="*邮箱格式不对" :disabled="isEdit"></w-input>
          </div>
        </div>
        <div class="e-item">
          <span class="title">员工姓名</span>
          <div class="o-select dis-block">
            <w-input :holder="`请填写`" v-model="addParams.trueName" rule="isEmpty" error="*此项必填" :disabled="isEdit"></w-input>
          </div>
        </div>
        <div class="e-item">
          <span class="title">员工工号</span>
          <div class="o-select dis-block">
            <w-input :holder="`请填写`" v-model="addParams.workNum" :disabled='true' ></w-input>
          </div>
        </div>
        <div class="e-item">
          <span class="title">手机号码</span>
          <div class="o-select dis-block">
            <w-input :holder="`请填写`" v-model="addParams.safeMobile" rule="isEmpty|isMobile" error="*此项必填|*手机号为11位" :disabled="isEdit"></w-input>
          </div>
        </div>
        <div class="e-item" v-if="!isEdit">
          <span class="title">入职时间</span>
          <div class="o-select dis-block">
            <w-date-picker language="ch" placeholder="请选择入职时间"  v-model="addParams.entryTime" rule="isEmpty" error="*此项必填" ></w-date-picker>
          </div>
        </div>
        <!-- 操作权限 -->
        <all-per :isEdit='isEdit' :permissionList='permissionList' :defaultChecked='defaultChecked' @get-checkedPermission='_getCheckedPermission'></all-per>
      </div>
      <div class="sure-btn" v-if="!isEdit">
        <button type="submit">确定</button>
      </div>
    </w-form-validate>
  </div>
</template>

<script>
import { apiSystemMange } from 'js/api'
import { mapGetters } from 'vuex'
import AllPermission from './components/allPermission'

export default {
  data() {
    return {
      queryPar: {
        accessToken: ''
      },
      permissionList: [], // 权限集合
      threePermission: 'select', // 三级菜单 增/删/改/查 权限
      // 新增员工 -- 参数
      addParams: {
        accessToken: '',
        threeMenuCode: this.$route.query.three || '',
        id: Number(this.$route.query.id) || '',
        userName: '',
        password: '',
        twoPassword: '',
        departmentId: '',
        safeMobile: '',
        entryTime: '',
        workNum: Math.floor(Math.random()*1000000) + '',
        alias: '',
        mail: '',
        roleId: '',
        trueName: ''
      },
      checkedPermission: [], // 选中的权限列表
      defaultChecked: [],
      // 查询角色对应的权限 -- 参数
      queryRolePar: {
        accessToken: '',
        threeMenuCode: this.$route.query.three || '',
        id: ''
      },
      // 保存权限 -- 参数
      saveParams: {
        accessToken: '',
        threeMenuCode: this.$route.query.three || '',
        authIds: [],
        id: ''
      },
      // 编辑时，查询员工信息及权限 -- 参数
      editParams: {
        accessToken: '',
        threeMenuCode: this.$route.query.three || '',
        type: 'edit',
        id: Number(this.$route.query.id) || 0
      },
      isEdit: !!this.$route.query.see || false,
      roleList: [], // 角色列表
      departList: [], // 部门列表
      name: {
        role: '',
        depart: '',
        name: ''
      }
    }
  },
  created() {
    this._getPermission()
    this._getRoleDepartList()
  },
  computed: {
    ...mapGetters(['token'])
  },
  components: {
    'all-per': AllPermission
  },
  methods: {
    // 获取该员工下的角色/部门列表
    _getRoleDepartList() {
      let par = {
        accessToken: this.token,
        threeMenuCode: this.$route.query.three || '',
        type: 'updateUser'
      }
      apiSystemMange.getRoleLis(par).then(data => {
        const list = data.data || {}
        if (list && list.length == 0) return
        this.roleList = list.PlatformRole.map(role => {
          return {
            value: role.id,
            label: role.roleName
          }
        })
        this.roleList.unshift({value: '', label: '请选择'})
      })
      apiSystemMange.getDepartLis(par).then(data => {
        const res = data.data || {}
        if (res && res.length == 0) return
        this.departList = res.department.map(val => {
          return {
            value: val.id,
            label: val.departmentName
          }
        })
        this.departList.unshift({value: '', label: '请选择'})
      })
    },
    // 获取权限列表
    _getPermission() {
      this.queryPar.accessToken = this.token
      apiSystemMange.getMenuLis(this.queryPar).then(data => {
        this.permissionList = data.data.menu
        this.permissionList.forEach(v => {
          this.$set(v, 'isShowListItem', true)
          this.$set(v, 'isChecked', false)
          // 二级 循环
          v.twoList.forEach(val => {
            this.$set(val, 'isShowListItem', true)
            this.$set(val, 'isChecked', false)
            // 三级 循环
            if (val.threeList && val.threeList.length > 0) {
              val.threeList.forEach(value => {
                this.$set(value, 'isShowListItem', true)
                this.$set(value, 'isChecked', false)
                this.$set(value, 'add', false)
                this.$set(value, 'update', false)
                this.$set(value, 'delete', false)
                this.$set(value, 'select', false)
              })
            }
          })
        })
        // 编辑/查看 员工时
        if (this.$route.query.id) {
          this._queryEmployInfo()
        }
      })
    },
    // 角色改变，选中该角色对应的基本权限
    changeRole() {
      this.queryRolePar.accessToken = this.token
      if (this.addParams.roleId) {
        this.queryRolePar.id = this.addParams.roleId
        apiSystemMange.queryRolePermission(this.queryRolePar).then(data => {
          this.defaultChecked = data.data.menu || []
        })
      } else {
        this.defaultChecked = []
      }
    },
    checkPwassword() {
      if (this.addParams.twoPassword) {
        if (this.addParams.password != this.addParams.twoPassword) {
          this.$toast('两次输入的值不一样', () => {
            this.addParams.twoPassword = ''
          })
        }
      }
    },
    checkUserName() {
      if (this.addParams.userName) {
        if (this.$route.query.id) {
          if (this.addParams.userName == this.name.name) return
        }
        apiSystemMange.checkUser({userName: this.addParams.userName}).then(req => {
          if (req.code != '310') return
          this.$toast('该用户名已存在')
        })
      }
    },
    // 保存 提交
    saveAddEmployee() {
      if (!this.addParams.roleId) {
        this.$toast('请选中员工角色')
        return
      }
      if (!this.addParams.departmentId) {
        this.$toast('请选中员工部门')
        return
      }
      if (!this.addParams.entryTime) {
        this.$toast('请选中员工入职时间')
        return
      }
      if (this.$route.query.id) {
        if (this.addParams.userName == this.name.name) {
          this.submitSave()
          return
        }
      }
      apiSystemMange.checkUser({userName: this.addParams.userName}).then(req => {
        if (req.code == 310) {
          this.$toast('该用户名已存在')
          return
        }
        this.submitSave()
      })
    },
    submitSave() {
      // 新增员工
      this.addParams.accessToken = this.token
      this.addParams.password = md5(this.addParams.password)
      this.addParams.twoPassword = md5(this.addParams.twoPassword)
      if (this.$route.query.id) {
        // 修改员工
        apiSystemMange.updateEmploy(this.addParams).then(data => {
          if (data.code != '200') return
          // 保存权限
          this.$toast('修改成功,正在保存权限', () => {
            this.saveParams.accessToken = this.token
            this.saveParams.authIds = this.checkedPermission
            this.saveParams.id = this.$route.query.id
            apiSystemMange.savePermission(this.saveParams).then(req => {
              if (req.code != '200') return
              this.$toast('员工权限保存成功', () => {
                this.$router.push(`/employeeMange/list?three=${this.$route.query.three}`)
              })
            })
          })
        })
      } else {
        // 新增员工
        apiSystemMange.addEmploy(this.addParams).then(data => {
          if (data.code != '200') return
          // 保存权限
          this.$toast('员工新增成功,正在保存权限', () => {
            this.saveParams.accessToken = this.token
            this.saveParams.authIds = this.checkedPermission
            this.saveParams.id = data.data.id
            apiSystemMange.savePermission(this.saveParams).then(req => {
              if (req.code != '200') return
              this.$toast('员工权限保存成功', () => {
                this.$router.push(`/employeeMange/list?three=${this.$route.query.three}`)
              })
            })
          })
        })
      }
    },
    // 查看员工的信息及权限
    _queryEmployInfo() {
      this.editParams.accessToken = this.token
      // 员工信息
      apiSystemMange.getEmployInfo(this.editParams).then(data => {
        if (data.code != '200') return
        this.addParams.userName = data.data.bean.userName || ''
        this.name.name = data.data.bean.userName
        this.name.depart = data.data.bean.department.departmentName || ''
        this.name.role = data.data.bean.role.roleName || ''
        this.addParams.departmentId = data.data.bean.department.id || ''
        this.addParams.safeMobile = data.data.bean.safeMobile || ''
        this.addParams.entryTime = data.data.bean.entryTimeString.substring(0, 10) || ''
        this.addParams.workNum = data.data.bean.workNum || ''
        this.addParams.alias = data.data.bean.alias || ''
        this.addParams.mail = data.data.bean.mail || ''
        this.addParams.roleId = data.data.bean.role.id || ''
        this.addParams.trueName = data.data.bean.trueName || ''
      })
      // 员工权限
      apiSystemMange.editEmploy(this.editParams).then(data => {
        if (data.code != '200') return
        if (data.data.menu) {
          this.defaultChecked = data.data.menu
        }
      })
    },
    _getCheckedPermission(data) {
      this.checkedPermission = data
    }
  }
}
</script>

<style lang="scss" scoped>
@import '../../scss/_var.scss';
.e-add {
    border-bottom: 2px solid #D7D7D7;
    .e-item {
      display: inline-block;
      margin-top: 20px;
      margin-left: 40px;
      position: relative;
      .title {
        width: 56px;
        display: inline-block;
        margin-left: 20px;
        font-size: 12px;
      }
      .dis-block {
        display: inline-block;
        width: 170px;
      }
    }
    .e-item:nth-of-type(4n+1) {
      margin-left: 0;
    }
    .menu {
      margin: 0 24px;
      li {
        margin-top: 24px;
        position: relative;
        margin-bottom: 24px;
      }
      span {
        font-size: 13px;
      }
    }
    .one-menu {
      position: relative;
      top: -42px;
      left: 56px;
      width: 1110px;
      margin-right: 0;
    }
    .three-menu li{
      display: inline-block;
      margin-right: 40px;
      margin-top: 0;
      margin-bottom: 0;
      &:last-child {
        margin-right: 0;
      }
      & > span {
        display: inline-block;
        margin-top: 24px;
      }
    }
}
.ico-drop {
    position: absolute;
    top: 8px;
    margin-left: 5px;
    z-index: 2;
    width: 0;
    height: 0;
    border: 7px solid transparent;
    border-top-color: #444;
    transition: all .2s;
    &.actived {
    transform: rotate(180deg) translateY(8px);
    }
}
.sure-btn {
  text-align: center;
  margin: 30px auto;
  button {
    background: $color-main;
    width: 90px !important;
    height: 32px;
    border-radius: 5px;
    color: #fff;
  }
}
</style>


